<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>任务管理</title>
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<script src="/style/public/publicStyle.js"></script>
	<style type="text/css">
		.layui-table-click {
			background-color:#def0f5;
		}
	</style>
</head>

<body >
<div class="weadmin-nav">
			<span class="layui-breadcrumb" style="visibility: visible;">
			<a href="">任务管理</a><span lay-separator="">/</span>
			<a>
				<cite>指标SQL配置</cite></a>
			</span>
	<a class="layui-btn layui-btn-sm" style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);" title="刷新">
		<i class="layui-icon" style="line-height:30px">ဂ</i></a>
</div>


<div class="layui-row">
	<div class="layui-col-md3">
		<table class="layui-hide" id="tableDataList" lay-filter="mainTableFilter"></table>
	</div>
	<div class="layui-col-md9">
		<form class="layui-form" action="">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">事实表选择</label>
					<div class="layui-input-inline">
						<select name="modules" lay-filter="mainSelectIdFilter" disabled=true lay-verify="required" lay-search="" style="width: 300px" id="mainSelectId">
							<option value="">直接选择或搜索选择</option>
						</select>
					</div>
				</div>
				<div class="layui-inline">
					<button type="button" class="layui-btn" onclick="edit()" id="editButton">编辑</button>
				</div>
			</div>
		</form>

		<!--表格-->
		<div class="weadmin-body">
			<div class="layui-row">
				<div class="layui-bg-gray" style="padding: 30px;" id="dwTbtables">
				</div>
			</div>
			<fieldset class="layui-elem-field">
				<legend>依赖维度</legend>
				<div class="layui-field-box">
					<table class="layui-table" id="dimTb">
						<thead>
						<tr>
							<th>事实表</th>
							<th>事实维度</th>
							<th>维度描述</th>
							<th>维度表</th>
							<th>操作</th>
						</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</fieldset>
			<div class="layui-row">
				<form class="layui-form layui-from-pane" id="formId" style="margin-top:20px;" disabled lay-filter="tableForm">
					<input type="hidden" name="idIndex" id="idIndex"/>
					<input type="hidden" name="naIndex" id="naIndex"/>
					<input type="hidden" name="idIndexsql"/>
					<div class="layui-form-item">
						<div class="layui-row">
							<div class="layui-col-md5">
								<label class="layui-form-label">时间字段</label>
								<div class="layui-input-block">
									<input type="text" name="grpDtfld" id="grpDtfld"  required  lay-verify="required" autocomplete="off" placeholder="请输入目标表" class="layui-input">
								</div>
							</div>
							<div class="layui-col-md5">
								<label class="layui-form-label">value值</label>
								<div class="layui-input-block">
									<input type="text" name="sqlVal" id="sqlVal"  required  lay-verify="required" autocomplete="off" placeholder="请输入目标表" class="layui-input">
								</div>
							</div>
						</div>
					</div>
					<div class="layui-form-item">
						<div class="layui-row">
							<div class="layui-col-md5">
								<label class="layui-form-label">JOIN条件</label>
								<div class="layui-input-block">
									<textarea name="sqlOn" id="sqlOn" placeholder="多个条件;分割" rows="10" class="layui-textarea"></textarea>
								</div>
							</div>
							<div class="layui-col-md5">
								<label class="layui-form-label">过滤条件</label>
								<div class="layui-input-block">
									<textarea name="sqlWhere" id="sqlWhere" placeholder="机构、时间区间排除" rows="10" class="layui-textarea"></textarea>
								</div>
							</div>
						</div>
					</div>

					<div class="layui-form-item" style="margin-top:40px;display:none" id="formButton">
						<div class="layui-input-block">
							<button class="layui-btn" lay-submit="" lay-filter="demo11">提交</button>
							<button type="reset" class="layui-btn layui-btn-primary">重置</button>
							<button type="button" class="layui-btn" lay-filter="cancel" id="cancel">返回</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

<script type="text/html" id="toolbarDemo">
	<input class="text" style="height:35px;width:257px;" name="" id="hiddenFilter" placeholder="根据表名过滤" />
</script>

</body>
<script>
    var edit = function() {
        var idIndex = $("#idIndex").val();
        if(idIndex=="") {
            layer.alert("请先选择指标");
            return;
        }
        $("#mainSelectId").attr("disabled", false);
        layui.form.render('select');
        $("#editButton").hide();
        $("#formButton").css('display','block');
    };

    var tbCheckBoxClick = function(elem) {
        var tds = $(elem).parent().siblings("td");
        var dimFld = tds[0].innerText;
        var dimFldNa = tds[1].innerText;
		var tbNa = tds[2].innerText;
		if(elem.checked) {
		    if($("#"+dimFld).length>0) {
                layer.alert("该维度已从其他事实表添加");
		        return;
			}
            $.ajax({
                url: '/etl/mdMedDim/getById',
                type:'get',
                data:{"idDim":dimFld},
                success: function(data1) {
                    var data =data1.data; //提出返回数据中的data
                    if(data!=null) {
                        var tr = "<tr id='"+dimFld+"'><td>"+tbNa+"</td><td>"+dimFld+"</td><td>"+dimFldNa+"</td><td>"+data.tbDim+"</td>"+
                            "<td><button type=\"button\" class=\"layui-btn layui-btn-xs\">字段</button><button type=\"button\" class=\"layui-btn layui-btn-xs\">值</button></td></tr>";
                        $("#dimTb tbody:last").append(tr);
                    } else {
                        $(elem).attr("checked", false);
                    }
                }
            });
		} else {
		    $("#"+dimFld).remove();
		}
    };
    var deleteDwTb = function (elem) {
        var del = true;
        $(elem).parent().find("input:checkbox").each(function (index,data) {
			if(this.checked) {
                layer.alert("请先取消已勾选的维度");
                del = false;
                return;
			}
        });
        if(del) {
            $(elem).parent().remove();
		}
    };
	layui.use(['util','laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function(){
		var util = layui.util;
		var laydate = layui.laydate //日期
				,laypage = layui.laypage //分页
				,layer = layui.layer //弹层
				,table = layui.table //表格
				,carousel = layui.carousel //轮播
				,upload = layui.upload //上传
				,element = layui.element //元素操作
				,form = layui.form;
        table.render({
            elem: '#tableDataList'
            ,even: false //开启隔行背景
            ,cellMinWidth: 80
            ,toolbar: '#toolbarDemo'
            ,defaultToolbar:[]
            ,url:'/etl/baseIndex/findByPage'
            ,cols: [[
                ,{field:'pk', title: 'ID', hide:true}
                ,{field:'cd', title: '编码'}
                ,{field:'na', title: '名称'}
            ]]
            ,page: true
			,limit:15
        });

		$("body").on("keypress","#hiddenFilter",function(event){
			var content = $(this).val();
			if(event.keyCode == '13') {
				//执行重载
				table.reload('tableDataList', {
					page: {
						curr: 1 //重新从第 1 页开始
					}
					,where: {
						filter: content		//在表格中进行搜索
					}
				});
				$("#hiddenFilter").val(content);
			}
		});

        var reloadIndexSqlData = function () {
            var idIndex = $("#idIndex").val();
            if (idIndex == "") {
                layer.alert("请先选择指标");
                return;
            }
            $.ajax({
                url: '/etl/etlIndexsql/getByIndex',
                type: 'get',
                data: {"idIndex": idIndex},
                success: function (data1) {
                    var data = data1.data; //提出返回数据中的data
                    var baseIndexConfFdList = data.etlIndexsqlDimfldList;
                    var tbFldsMap = data.tbFldsMap;
                    //var
                    $("#formId")[0].reset();
                    layui.form.val("tableForm", data.etlIndexsql);
                    $("#sqlOn").val(data.sqlOn);
                    $("#dimTb tbody tr").remove();
                    var fd;
                    if (baseIndexConfFdList != null) {
                        for (var i = 0; i < baseIndexConfFdList.length; i++) {
                            fd = baseIndexConfFdList[i];
                            var tr = "<tr id='" + fd.idPubfld + "'><td>" + fd.idTb + "</td><td>" + fd.idPubfld + "</td><td>" + fd.idPubfld + "</td><td>" + fd.idTb + "</td>" +
                                "<td><button type=\"button\" class=\"layui-btn layui-btn-xs\">字段</button><button type=\"button\" class=\"layui-btn layui-btn-xs\">值</button></td></tr>";
                            $("#dimTb tbody:last").append(tr);
                        }
                    }
                    $("#dwTbtables").find(".layui-col-space15").remove();
                    var tableCdAndNa;
                    if (tbFldsMap != null) {
                        createOneRow();
                        for (var key in tbFldsMap) {
                            var row = $("#dwTbtables").find(".layui-col-space15").last();
                            if (row.attr("size") == 3) {
                                createOneRow();
                                row = $("#dwTbtables").find(".layui-col-space15").last();
                            }
                            tableCdAndNa = key.split("+++");
                            if (tableCdAndNa.length == 2) {
                                createDimTableByData(row[0], tableCdAndNa[0], tableCdAndNa[1]+'('+tableCdAndNa[0]+')', tbFldsMap[key]);
                            }
                        }
                    }
                }
            });
        };
        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(mainTableFilter)', function(obj){
            var data = obj.data;
            $("#idIndex").val(data.pk);
            $("#naIndex").val(data.na);
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            reloadIndexSqlData();
        });
        $.ajax({
            url: '/etl/mdMedTb/find',
            type:'post',
            dataType:'json',
            contentType:'application/json;charset=UTF-8',
            data:JSON.stringify({"sdTbca":"DW"}),
            success: function(data1) {
                var data =data1.data; //提出返回数据中的data
                form.val("tableForm",data);
                if (data!== null) {
                    $.each(data, function(index, item) { //循环加入 data的元素
                        $("#mainSelectId").append('<option value="'+item.idTb+'">'+item.na+'('+item.idTb+')</option>');
                    });
                    form.render('select');
                };
            }
        });
        var createDimTableByData = function (element,selectValue,selectHtml,data) {
            var row = $(element);
            if (data!== null) {
                var tbTop = '<div class="layui-col-md4" style="overflow:auto;zoom:1;" id="'+selectValue+'">'+
                    '<span style="float: right;font-size:24px;cursor:pointer;z-index: 11;position: relative;" onclick="deleteDwTb(this)">×</span>'+
                    '<div class="layui-card">'+
                    '<div class="layui-card-header">'+selectHtml+'</div>'+
                    '<div class="layui-card-body">'+
                    '<table class="layui-table">'+
                    '<colgroup><col width="50"><col><col></colgroup>'+
                    '<thead><tr><th></th><th>表字段</th><th>字段描述</th></tr></thead>'+
                    '<tbody>';
                var tbTail = '</tbody>'+
                    '</table>'+
                    '</div>'+
                    '</div>'+
                    '</div>';
                var tbMiddle = '';
                $.each(data, function(index, item) { //循环加入 data的元素
                    tbMiddle += ('<tr>'+
                    '<th><input type="checkbox" onclick="tbCheckBoxClick(this)" '+(item.fgCheck=="1"?'checked':'')+'></th>'+
                    '<td>'+item.idPubfld+'</td>'+
                    '<td>'+item.na+'</td>'+
                    '<td style="display: none">'+selectValue+'</td>'+
                    '</tr>');
                });
                row.html(row.html()+tbTop+tbMiddle+tbTail);
                row.attr("size",row.attr("size")+1);
            };
		}
        var createDimTable = function (element,selectValue,selectHtml) {
            var row = $(element);
            $.ajax({
                url: '/etl/mdMedTbFld/findValidTbField',
                type:'get',
                data:{"idTb":selectValue},
                success: function(data1) {
                    var data =data1.data; //提出返回数据中的data
                    createDimTableByData(element,selectValue,selectHtml,data);
                }
            });
        };
        var createOneRow = function() {
            var html = '<div class="layui-row layui-col-space15" size="0"></div>';
            $("#dwTbtables").append(html);
		};
        $(document).on('click','#cancel',function(){
            var idIndex = $("#idIndex").val();
            if(idIndex=="") {
                layer.alert("请先选择指标");
                return;
            }
            $("#mainSelectId").attr("disabled",true);
            form.render('select');
            $("#editButton").show();
            $("#formButton").css('display','none');
            reloadIndexSqlData();
            return false;
        });

        form.on('submit(demo11)', function(massage) {
            var confJosn = massage.field;
            var confFdJosn = "[";
            $("#dimTb").find("tbody tr").each(function(){
                var tdArr = $(this).children();
                var pkTb = tdArr[0].innerHTML;
                var pkPubfd = tdArr[1].innerHTML;
				if(confFdJosn!="[") {
                    confFdJosn += ',';
				}
				confFdJosn += '{"idTb":"'+pkTb+'","idPubfld":"'+pkPubfd+'"}';
            });
            confFdJosn += ']';
            var mainTable = $("#dwTbtables").find(".layui-col-md4").first().attr("id");
            var idIndex = $("#idIndex").val();
            if(mainTable!=undefined && idIndex!=""){
                $.ajax({
                    url:'/etl/etlIndexsql/save',
                    type:'post',
                    dataType:'json',
                    contentType:'application/json;charset=UTF-8',
                    data:JSON.stringify({"etlIndexsql":confJosn,"sqlOn":$("#sqlOn").val(),"mainTable":mainTable,"indexsqlDimfldList":JSON.parse(confFdJosn)}),
                    success:function (msg) {
						layer.alert("保存成功");
						$("#mainSelectId").attr("disabled",true);
						form.render('select');
						$("#editButton").show();
						$("#formButton").css('display','none');
						reloadIndexSqlData();
                    }
                });
            } else {
                if(mainTable==undefined) {
                    layer.alert("该维度已从其他事实表添加");
				} else if(idIndex=="") {
                    layer.alert("请先选择指标");
                }
            }
            return false;
        })
        form.on('select(mainSelectIdFilter)', function(data){
            if($("#"+data.value).length>0) {
				return;
			}
            var row = $("#dwTbtables").find(".layui-col-space15").last();
            if(row.length==0) {
                createOneRow();
			} else {
                if(row.attr("size")==4) {
                    createOneRow();
				}
			}
            row = $("#dwTbtables").find(".layui-col-space15").last();
            createDimTable(row[0],data.value,this.innerHTML);
        });

	});
</script>

</html>